#include "papir.h"
#include "status.h"
#include <QMessageBox>
#include <QStatusBar>

Papir::Papir(QWidget *parent)
    : QWidget(parent)
{
    Nastaveni nastaveni;
    nastaveni.exec();
    if(nastaveni.lokalni->vratHrace() != NULL)
    {
        tabulka = nastaveni.lokalni->vratHrace();
        emit chatVisible(false);
    }
    else
    {
        tcpClient = nastaveni.sitova->tcpClient;
        connect(tcpClient,SIGNAL(readyRead()),this,SLOT(onNewData()));
        tabulka = nastaveni.sitova->vratHrace();
    }

    velikostPolicka = 20;

    tabulka->zmenAktualniho();
    emit playerChanged(tabulka->aktualni());
}

void Papir::paintEvent(QPaintEvent *event)
{

  QPen pen(Qt::black, 1, Qt::SolidLine);

  QPainter painter(this);
  painter.setPen(pen);

  QVector <QRect> papir(0);
  for(int i = 0;i<this->size().width()/velikostPolicka;i++)
  {
      for(int j = 0;j<this->size().height()/velikostPolicka;j++)
      {
          papir.append(QRect(i*velikostPolicka,j*velikostPolicka,velikostPolicka,velikostPolicka));
      }
  }
  painter.drawRects(papir);

  if(tabulka !=NULL)
  {
      pen.setWidth(2);

      pen.setColor(*tabulka->vratHrace(0)->zjistiBarvu());
      painter.setPen(pen);
      painter.drawPath(*tabulka->vratHrace(0)->zjistiGrafiku());
      if(tabulka->vratHrace(0)->zjistiTahy()->size()>0)
      {
          painter.fillRect(*tabulka->vratHrace(0)->zjistiTahy()->last().getX()*velikostPolicka,
                           *tabulka->vratHrace(0)->zjistiTahy()->last().getY()*velikostPolicka,
                           velikostPolicka,velikostPolicka,
                           Qt::Dense7Pattern);
      }

      pen.setColor(*tabulka->vratHrace(1)->zjistiBarvu());
      painter.setPen(pen);
      painter.drawPath(*tabulka->vratHrace(1)->zjistiGrafiku());
      if(tabulka->vratHrace(1)->zjistiTahy()->size()>0)
      {
          painter.fillRect(*tabulka->vratHrace(1)->zjistiTahy()->last().getX()*velikostPolicka,
                           *tabulka->vratHrace(1)->zjistiTahy()->last().getY()*velikostPolicka,
                           velikostPolicka,velikostPolicka,
                           Qt::Dense7Pattern);
      }
  }

  painter.end();
}

void Papir::mousePressEvent(QMouseEvent * event)
{
    if( *tabulka->aktualni()->zjistiTyp() == REMOTE) return;
    zapisTah(event->x()/velikostPolicka,event->y()/velikostPolicka);
    if(tcpClient != NULL)
    {
        QByteArray tmp;
        QDataStream out(&tmp, QIODevice::WriteOnly);
        Tah neco(event->x()/velikostPolicka,event->y()/velikostPolicka);
        neco.serialize(out);
        tmp.prepend("TAH;");
        this->tcpClient->write(tmp);
        this->tcpClient->flush();
    }
}

void Papir::zapisTah(int x, int y)
{
    if(tabulka->vratHrace(0)->existujeTah(x,y)
    || tabulka->vratHrace(1)->existujeTah(x,y)
    ) return;
    tabulka->aktualni()->pridejTah(x,y);
    this->vykresliObjekt(x,y);
    if (tabulka->aktualni()->checkForVictory())
    {
        QMessageBox vyhra;
        vyhra.setText(QString("%1 vyhrál/a.").arg(*tabulka->aktualni()->zjistiJmeno()));
        vyhra.setInformativeText("Přejete si vyčistit hrací plochu?");
        vyhra.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
        int ret = vyhra.exec();
        switch (ret)
        {
        case QMessageBox::No:
            break;
        case QMessageBox::Yes:
            tabulka->vratHrace(0)->zjistiGrafiku()->operator =(QPainterPath());
            tabulka->vratHrace(1)->zjistiGrafiku()->operator =(QPainterPath());
            tabulka->vratHrace(0)->zjistiTahy()->clear();
            tabulka->vratHrace(1)->zjistiTahy()->clear();
            break;
        }
    }

    tabulka->zmenAktualniho();
    emit playerChanged(tabulka->aktualni());
}

void Papir::vykresliObjekt(int x, int y)
{
    switch(*tabulka->aktualni()->zjistiZnak())
    {
    case 0:
        this->vykresliKrizek(x,y);
        break;
    case 1:
        this->vykresliKolecko(x,y);
        break;
    };
    repaint();

}

void Papir::vykresliKrizek(int x, int y)
{
    (*tabulka->aktualni()->zjistiGrafiku()).moveTo(x*velikostPolicka+3, y*velikostPolicka+3);
    (*tabulka->aktualni()->zjistiGrafiku()).lineTo(x*velikostPolicka+velikostPolicka-3, y*velikostPolicka+velikostPolicka-3);
    (*tabulka->aktualni()->zjistiGrafiku()).moveTo(x*velikostPolicka+velikostPolicka-3, y*velikostPolicka+3);
    (*tabulka->aktualni()->zjistiGrafiku()).lineTo(x*velikostPolicka+3, y*velikostPolicka+velikostPolicka-3);
}

void Papir::vykresliKolecko(int x, int y)
{
    (*tabulka->aktualni()->zjistiGrafiku()).moveTo(x*velikostPolicka+3, y*velikostPolicka+3);
    (*tabulka->aktualni()->zjistiGrafiku()).addEllipse(x*velikostPolicka+3, y*velikostPolicka+3,velikostPolicka-6,velikostPolicka-6);
}

Hraci * Papir::vratHrace()
{
    return tabulka;
}

void Papir::onNewData()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(this->sender());
    QByteArray rawdata = socket->readAll();
    QList<QByteArray> args = rawdata.split(';');
    QString command = args.takeFirst();
    QDataStream stream(args.takeFirst());
    if(command=="TAH")
    {
        Tah neco(stream);
        zapisTah(*neco.getX(), *neco.getY());
    } else if (command == "CHAT")
    {
        QString chat;
        stream >> chat;
        emit newChatMessage(chat);
    }

}

void Papir::onNewMessage(QString message)
{
    emit newChatMessage(message);
    QByteArray tmp;
    QDataStream out(&tmp, QIODevice::WriteOnly);
    out << message;
    tmp.prepend("CHAT;");
    this->tcpClient->write(tmp);
    this->tcpClient->flush();

}
